package com.ukao.steward.ui.valetRunners.bingCard;


import android.content.DialogInterface;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Handler;
import android.os.RemoteException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.sunmi.payservice.hardware.aidl.AidlConstants;
import com.sunmi.payservice.hardware.aidl.HardwareOpt;
import com.sunmi.payservice.hardware.aidl.ReadCardCallback;
import com.sunmi.payservice.hardware.aidl.bean.PayCardInfo;
import com.ukao.steward.R;
import com.ukao.steward.base.BaseApplication;
import com.ukao.steward.base.BaseFragment;
import com.ukao.steward.bean.UserInfoCard;
import com.ukao.steward.consts.Constant;
import com.ukao.steward.consts.SaveParams;
import com.ukao.steward.eventbus.ReadCardEvent;
import com.ukao.steward.retrofit.ApiCallback;

import com.ukao.steward.util.CheckUtils;
import com.ukao.steward.util.L;
import com.ukao.steward.util.StringByteUtils;
import com.ukao.steward.util.T;
import com.ukao.steward.widget.ClearEditText;

import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 读卡
 */
public class ReadCardFragment extends BaseFragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.back_btn)
    ImageView backBtn;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.title_layout)
    RelativeLayout titleLayout;
    @BindView(R.id.read_card_text)
    TextView readCardText;
    Unbinder unbinder;
    protected NfcAdapter nfcAdapter;
    @BindView(R.id.card_num)
    ClearEditText cardNum;
    @BindView(R.id.bing_card)
    Button bingCard;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private String rfidSecret="";
    private  boolean isVisibles=false;
    private  boolean isReadCard=false;
    public  HardwareOpt mHardwareOpt;
    PayCardInfo payCardInfo;
    int keyType = 0;
    //块号
    int blockAddress = 4;
    private Handler  mHandler=new Handler();


    public static ReadCardFragment newInstance(String param1, String param2) {
        ReadCardFragment fragment = new ReadCardFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_read_card, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();

        return view;
    }


    @Override
    protected void initView() {
        isVisibles=true;
        setStatusBarTintColor(R.color.normal_blue);
        titleLayout.setBackgroundColor(getColors(R.color.colorPrimary));
        title.setText("绑卡");
        mHardwareOpt = BaseApplication.mHardwareOpt;





    }


    /**
     * 读卡
     */
    private void postDelayedReadCard() {
        mHandler.removeCallbacksAndMessages(null);
        L.i("isReadCard="+isReadCard);
        if (isReadCard&&CheckUtils.isMIUIDevices()&&isAdded()){
            mHandler.postDelayed(() -> swingCard(), 1000);
        }


    }



    /**
     * 刷卡
     */
    private void swingCard() {

        try {
            //支持M1卡
            int allType = AidlConstants.CardType.MIFARE;
            mHardwareOpt.checkCard(allType, mReadCardCallback, 60);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    ReadCardCallback mReadCardCallback = new ReadCardCallback.Stub() {
        @Override
        public void onCardDetected(final PayCardInfo cardInfo) throws RemoteException {
            payCardInfo = cardInfo;
            if (isAdded()) mHandler.post(() -> m1auth());


        }

        @Override
        public void onError(final int i, final String s) throws RemoteException {
            postDelayedReadCard();
        }

        @Override
        public void onStartCheckCard() throws RemoteException {
        }
    };

    /**
     * 授权
     */
    private void m1auth() {
        try {
            byte[] key = StringByteUtils.hexStringToBytes("31455433494F"); //密码
            int result = mHardwareOpt.mifareAuth(keyType, blockAddress, key);
            if (result == 0) {
                m1readblock();

            } else {
                T.show(getString(R.string.m1auth_1error));
                postDelayedReadCard();
            }
        } catch (Exception e) {
            e.printStackTrace();
            postDelayedReadCard();
            T.show(getString(R.string.m1auth_1error));

        }
    }

    /**
     * 读取块数据
     */
    private void m1readblock() {
        try {
            byte[] blockData = new byte[260];
            blockAddress=4;
            int blockResult = mHardwareOpt.mifareReadBlock(blockAddress, blockData);
            if (blockResult == 0) {
                 rfidSecret=StringByteUtils.convertHexToString(StringByteUtils.bytesToHexString(blockData));
                rfidSecret=rfidSecret.replace("�","").replace("\u0090","").trim();
                userInfoCard("");

            } else {

                T.show(getString(R.string.m1readblock));
                postDelayedReadCard();
            }

        } catch (RemoteException e) {
            e.printStackTrace();
            T.show(getString(R.string.m1readblock));
            postDelayedReadCard();
        }

    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        isVisibles=true;
        isReadCard=true;
        postDelayedReadCard();
    }

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        isReadCard=false;
        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Subscribe
    public void onEvent(ReadCardEvent event) {
        if (!isVisibles)return;
        switch (event.getMessage()) {
            case READCARD:/*读卡*/
                HashMap mData = (HashMap) event.getData();
                 String   secretKey=(String) mData.get(ARG_PARAM1);
                  if (CheckUtils.isEmpty(secretKey)) {
                      T.show("读取失败");
                      return;
                  }else{
                      rfidSecret=secretKey;
                  }
                 userInfoCard("");
                break;
            case NOSUPPORT:/*手机 不支持*/
                T.show("此手机不支持读卡");
                break;

        }
    }




    /**
     *  读卡请求
     * @param cardNumber  手动输入的卡号
     */
    public void userInfoCard(final String cardNumber) {
        if (isReadCard) showProgressDialog();
        HashMap mHashMap = new HashMap<String, String>();
        L.i("rfidSecret="+rfidSecret+"rfidSecret");
        if (!CheckUtils.isEmpty(cardNumber)){        mHashMap.put("rfidNo",cardNumber);}
        mHashMap.put("rfidSecret",rfidSecret);
        mHashMap.put("accessToken", SaveParams.getToken());
        addSubscription(apiStores().userInfoCard(Constant.createParameter(mHashMap)),
                new ApiCallback<UserInfoCard>() {
                    @Override
                    public void onSuccess(UserInfoCard model) {

                        if (model.getHttpCode() == 200) {
                            UserInfoCard muserInfoCard=model.getData();
                            isVisibles=false;
                            isReadCard=false;
                            if (muserInfoCard.getIsBinding()){
                                start(ClientFragment.newInstance(muserInfoCard,false),SINGLETASK);
                            }else{ /*未绑定*/
                                muserInfoCard.setRfidNo(cardNumber);
                                start(SearchUserFragment.newInstance(muserInfoCard,false),SINGLETASK);
                            }

                        } else {


                            T.show(model.getMsg());
                        }

                    }


                    @Override
                    public void onFinish() {

                        dismissProgressDialog();

                    }
                });

    }




    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);

        postDelayedReadCard();

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();

        mHandler.removeCallbacksAndMessages(null);
    }



    @OnClick({R.id.back_btn, R.id.bing_card})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.bing_card:

                String   strCardNum=getText(cardNum);
                if (CheckUtils.isEmpty(strCardNum)){
                    return ;
                }
                rfidSecret="";
                userInfoCard(strCardNum);

                break;



        }
    }



}
